package com.imooc.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import org.springframework.http.MediaType;

/**
 * 创建自定义的http服务响应处理类
 * SimpleChannelInboundHandler: 对于前端发来的请求来讲, 相当于入站(入境)
 * 泛型是HttpObject的原因: 我们是http请求, 所以消息的类型是HttpObject
 * @author liansen
 * @create 07-15-0:47
 */
public class HttpHandler extends SimpleChannelInboundHandler<HttpObject> {

    /*
        客户端与服务端建立连接后就会有channel, 消息是请求带过来的, 消息要从channel中去读取
        ctx: 上下文对象
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

        //获取当前用户连接的客户端channel
        Channel channel = ctx.channel();

        if(msg instanceof HttpRequest) {

            //打印客户端的地址
            System.out.println(channel.remoteAddress());

            //通过缓冲区定义发送的数据消息, 读写数据都是通过缓冲区进行数据交互
            ByteBuf content = Unpooled.copiedBuffer("hello netty", CharsetUtil.UTF_8);

            //构建Http Response
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);

            //为响应增加数据类型和长度
            //content-type  text/plain
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE);
            //content.readableBytes(): 消息的长度
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());

            //把响应的数据写到缓冲区，然后再刷到客户端
            ctx.writeAndFlush(response);

        }

    }
}
